package discovery;

import lombok.extern.log4j.Log4j;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Log4j
public class ServiceDiscovery {
    private ZooKeeper zooKeeper;
    private final Random random = new Random();
    public ServiceDiscovery(String connectString) {
        try {
            zooKeeper = new ZooKeeper(connectString, 40000, event -> {
                if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    log.info("已连接到ZooKeeper服务器");
                }
            });
        } catch (Exception e) {
            log.error("连接ZooKeeper失败:" + e.getMessage());
        }
    }

    public String discoverService(String serviceName) {
        try {
            String servicePath = "/services/" + serviceName;
            List<String> addresses = new ArrayList<>();

            // 获取节点方法下的所有可连接服务器
            List<String> children = zooKeeper.getChildren(servicePath, false);

            // 遍历服务器信息存储到addresses中
            for (String child : children) {
                String childPath = servicePath + "/" + child;
                byte[] addressBytes = zooKeeper.getData(childPath, false, null);
                String addressStr = new String(addressBytes);
                addresses.add(addressStr);
            }

            // 负载均衡——————随机选择方案
            // 随机选择一个服务实例的地址进行返回
            if (!addresses.isEmpty()) {
                String selectedAddress = addresses.get(random.nextInt(addresses.size()));
                log.debug("服务发现结果: " + selectedAddress);
                return selectedAddress;
            } else {
                log.error("服务未找到: " + serviceName);
                return null;
            }
        } catch (Exception e) {
            log.error("发现服务失败:" + e.getMessage());
            return null;
        }
    }
}
